<template>
  <div class="app-container" v-loading="loading">
    <el-col :span="4" :xs="24">
      <!--      <div class="logo-wrapper" style="text-align: center;padding-top: 20px;margin-bottom: 2px;padding-bottom: 0px">-->
      <!--        问题领域-->
      <!--      </div>-->
      <div class="head-container">
        <el-input
          v-model="domainName"
          placeholder="请输入领域名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
        />
      </div>
      <div class="head-container" style="min-width: 400px">
        <el-tree
          :data="domainOptions"
          :props="defaultProps"
          :filter-node-method="filterNode"
          node-key="id"
          :default-expanded-keys="[$route.query.domain]"
          ref="tree"
          @node-click="handleNodeClick"
        />
      </div>
    </el-col>
    <!--用户数据-->
    <el-col :span="20" :xs="24" style="padding-left: 20px">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="问题标题" prop="label">
          <el-input
            v-model="queryParams.label"
            placeholder="请输入问题标题"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="问题等级" prop="level">
          <el-select
            v-model="queryParams.level"
            placeholder="请选择问题等级"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_question_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="问题状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择问题状态"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:question:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="multiple"
            @click="handleUpdate"
            v-hasPermi="['system:question:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:question:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:question:export']"
            >导出</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="questionList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="显示顺序" align="center" prop="sort" />
        <!--      <el-table-column label="问题编码" align="center" prop="questionId" />-->
        <el-table-column
          label="问题标题"
          align="center"
          prop="label"
          show-tooltip-when-overflow
        />

        <el-table-column label="问题分数" align="center" prop="score" />
        <el-table-column label="问题等级" align="center" prop="level">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.sys_question_level"
              :value="scope.row.level"
            />
          </template>
        </el-table-column>

        <!--      <el-table-column label="问题领域" align="center" prop="domain" />-->
        <!--      <el-table-column label="问题内容" align="center" prop="detail" />-->
        <el-table-column label="问题状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.sys_normal_disable"
              :value="scope.row.status"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          align="center"
          prop="remark"
          show-tooltip-when-overflow
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="280px"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:question:edit']"
              >修改</el-button
            >

            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleWeight(scope.row)"
              v-hasPermi="['system:question:edit']"
              >配置权重</el-button
            >

            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:question:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-col>

    <!-- 添加或修改问题数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="权重" prop="weight">
          <el-input-number
            :min="0"
            :step="0.01"
            :precision="2"
            v-model="form.weight"
            placeholder="请输入权重"
          />
        </el-form-item>

        <draggable
          :list="form.optionConfigArr"
          :animation="340"
          group="selectItem"
          handle=".option-drag"
        >
          <div
            v-for="(item, index) in form.optionConfigArr"
            :key="index"
            class="select-item"
          >
            <div class="select-line-icon option-drag">
              <i class="el-icon-s-operation" />
            </div>
            <el-input
              v-model="item.label"
              placeholder="选项名"
              size="small"
              disabled
            />
            <el-input
              placeholder="选项值"
              size="small"
              :value="item.value"
              @input="setOptionValue(item, $event)"
            />
            <el-input-number
              v-model="item.score"
              style="width: 100%"
              placeholder="选项分数"
              size="small"
            />
            <el-input
              v-model="item.des"
              type="textarea"
              placeholder="请输入描述"
            />
            <!-- <div
              class="close-btn select-line-icon"
              @click="form.optionConfig.splice(index, 1)"
            >
              <i class="el-icon-remove-outline" />
            </div> -->
          </div>
        </draggable>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listQuestion,
  getQuestion,
  delQuestion,
  setQuestion,
  updateQuestion,
} from "@/api/system/question";
import { treeselect } from "@/api/system/questiondomain";
import draggable from "vuedraggable";
import { Message } from "element-ui";
import { isNumberStr } from "@/utils/index";

export default {
  name: "Question",
  dicts: [
    "question_show_type",
    "sys_normal_disable",
    "sys_question_level",
    "sys_yes_no",
  ],
  components: {
    draggable,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问题数据表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      domainOptions: undefined,
      domainName: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        label: null,
        sort: null,
        score: null,
        level: null,
        domain: this.$route.query.domain,
        detail: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sort: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" },
        ],
        score: [
          { required: true, message: "问题分数不能为空", trigger: "blur" },
        ],
        level: [
          { required: true, message: "问题等级不能为空", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    domainName(val) {
      this.$refs.tree.filter(val);
    },
  },

  created() {
    this.getList();
    this.getTreeselect();
  },
  activated() {
    this.getList();
  },
  methods: {
    /** 查询问题数据列表 */
    getList() {
      this.loading = true;
      listQuestion(this.queryParams).then((response) => {
        this.questionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTreeselect() {
      treeselect(this.queryParams).then((response) => {
        this.domainOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      console.log(value, data, "value, data");
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (!data?.children) {
        this.queryParams.domain = data.id;
        this.handleQuery();
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        questionId: null,
        weight: null,
        optionConfigArr: [
          {
            value: null,
            score: null,
            des: null,
          },
        ],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.domain = null;
      this.handleQuery();
    },
    setOptionValue(item, val) {
      item.value = isNumberStr(val) ? +val : val;
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.questionId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.open = true;
      // this.title = "添加问题数据";
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.replace({ name: "addQuestion" });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const questionId = row.questionId != null ? [row.questionId] : this.ids;
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.replace({
        name: "addQuestion",
        query: {
          questionIds: JSON.stringify(questionId),
          domain: this.queryParams.domain,
        },
      });
    },
    /** 配置分数权重操作 */
    handleWeight(row) {
      this.reset();
      this.open = true;
      this.title = "配置权重";
      const questionId = row.questionId;
      getQuestion(questionId).then((response) => {
        let detail = JSON.parse(response.data.detail).options;
        let optionConfig = JSON.parse(response.data.optionConfig);
        if (optionConfig) {
          optionConfig.forEach((item) => {});

          detail.map(
            (item) => (
              (item.score = optionConfig.filter(
                (option) => option.value == item.value
              )[0]?.score),
              (item.des = optionConfig.filter(
                (option) => option.value == item.value
              )[0]?.des)
            )
          );
        } else {
          detail.map((item) => ((item.score = 25), (item.des = item.label)));
        }

        this.form = {
          questionId,
          weight: response.data.weight,
          optionConfigArr: detail,
        };
      });

      // this.$store.dispatch("tagsView/delView", this.$route);
      // this.$router.replace({
      //   name: "addQuestion",
      //   query: { questionIds: JSON.stringify(questionId) },
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let flag = true;
          console.log(this.form);

          this.form.optionConfigArr.forEach((item) => {
            if (!item.score && flag && item.score != 0) {
              Message.warning("请输入分数");
              console.log("请输入分数");
              flag = false;
            }
          });
          this.form.optionConfig = JSON.stringify(this.form.optionConfigArr);
          if (flag) {
            console.log("1");
            setQuestion(this.form).then((response) => {
              console.log(response);
              if (response.code == 200) {
                Message.success("配置成功");
                this.open = false;
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const questionIds = row.questionId || this.ids;
      this.$modal
        .confirm('是否确认删除问题数据编号为"' + questionIds + '"的数据项？')
        .then(function () {
          return delQuestion(questionIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/question/export",
        {
          ...this.queryParams,
        },
        `question_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.select-item {
  display: flex;
  border: 1px dashed #fff;
  box-sizing: border-box;
  & .close-btn {
    cursor: pointer;
    color: #f56c6c;
  }
  & .el-input + .el-input {
    margin-left: 4px;
  }
  & .el-input-number + .el-input-number {
    margin-left: 4px;
  }
}
.select-item + .select-item {
  margin-top: 4px;
}
.select-item.sortable-chosen {
  border: 1px dashed #409eff;
}
.select-line-icon {
  line-height: 32px;
  font-size: 22px;
  padding: 0 4px;
  color: #777;
}
.option-drag {
  cursor: move;
}
</style>
